#!/usr/bin/env python
# -*- coding:utf8 -*-
"""
Author : mafei
Date   : 2019-12-22
"""

from .base import ViewSecurityBase
from mmonitor.models.mysql_db import UserModel
from mmonitor.common.code_verify import captcha_verify


class UserLoginView(ViewSecurityBase):

    def get(self, request):
        user_id = request.qget_string("user_id")

        return self.ok_response()

    def put(self, request):
        return self.ok_response()

    def post(self, request):

        password = request.bget_string("password")
        email = request.bget_string("email")
        verify = request.bget_dict("verify")

        if captcha_verify(verify) != 0:
            return self.error_response("验证码错误，请重新刷新页面")

        res = UserModel.get_or_none((UserModel.email == email) & (UserModel.password == password))
        if not res:
            return self.error_response("用户名/密码错误！")
        if not res.is_active:
            return self.error_response("您的账号还没激活，麻烦查收邮件并点击链接激活！")
        request.session['user'] = res.user_id
        # request.session['session_name'] = "admin"
        # request.session.set_test_cookie()
        return self.ok_response(data=res.user_id)
